import json
from rest_framework.generics import ListAPIView
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from .models import Host
from .serializer import HostModelSerializer
from .services.disk import disk_handler


class HostListAPIView(ListAPIView):  # 获取主机列表
    queryset = Host.objects.filter(status=1)
    serializer_class = HostModelSerializer


@csrf_exempt
def handle_post_msg(request, *args, **kwargs):  # 处理 cmdb_get 发送过来的数据
    content = request.body.decode('utf-8')
    msg_dict = json.loads(content)

    hostname = msg_dict.get('host')
    host_msg_dict = msg_dict.get('info')

    host_obj = Host.objects.filter(hostname=hostname).first()
    if not host_obj:
        return HttpResponse('host not found')

    disk_handler(host_obj, host_msg_dict['disk'])  # 处理硬盘信息

    return HttpResponse('ok')
